package com.wocai.jrt.orders.action;

import java.util.Date;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.wocai.jrt.orders.model.Orders;
import com.wocai.jrt.orders.model.PayTypeAudit;
import com.wocai.jrt.orders.model.Voucher;
import com.wocai.jrt.orders.service.spi.OrdersService;
import com.wocai.jrt.orders.service.spi.PayTypeAuditService;
import com.wocai.jrt.orders.service.spi.VoucherService;
import com.wocai.jrt.utils.ImgType;
import com.wocai.jrt.utils.MyFileUtils;

/**
 * 支付方式申请审核控制器
 * 
 * @author linbaolu
 * @date 2015-12-16 17:56:47
 */
@Controller
@RequestMapping("/payTypeAudit")
public class PayTypeAuditAction extends GenericAction<PayTypeAudit> {
	private static final Logger LOGGER = LoggerFactory.getLogger(PayTypeAuditAction.class);

	@Inject
	private PayTypeAuditService payTypeAuditServiceImpl;
	@Inject
	private OrdersService ordersServiceImpl;
	@Inject
	private VoucherService voucherServiceImpl;

	/**
	 * 执行实际的新增操作
	 * 
	 * @param model
	 *            要新增的数据
	 * @return 新增页面逻辑视图
	 */
	@ResponseBody
	@RequestMapping("/apply")
	public JsonBean apply(PayTypeAudit model) {
		JsonBean bean = new JsonBean();
		try {
			LOGGER.info("apply for other pay way, param=[{}]", JSON.toJSONString(model));

			if (StringUtils.isBlank(model.getOrderId())) {
				bean.setCode(0);
				bean.setMessage("订单id不能为空！");
				LOGGER.error("orderId is required.");
			}

			if (StringUtils.isBlank(model.getEmployeeId())) {
				bean.setCode(0);
				bean.setMessage("理财师id不能为空！");
				LOGGER.error("employeeId is required.");
			}

			if (StringUtils.isBlank(model.getEmployeeName())) {
				bean.setCode(0);
				bean.setMessage("理财师姓名不能为空！");
				LOGGER.error("employeeName is required.");
			}

			model.setId(ObjectId.get().toString());
			model.setApplyTime(new Date());
			int result = payTypeAuditServiceImpl.save(model);
			if (result == 1) {
				bean.setCode(1);
				bean.setMessage("申请成功！");
				LOGGER.info("save record success, payTypeAuditId=[{}]", model.getId());

				Orders data = new Orders();
				data.setOfflineAudit(1);

				Orders condition = new Orders();
				condition.setOrderId(model.getOrderId());
				ordersServiceImpl.updateBulks(data, condition);
				LOGGER.info("update order offlineAudit success, orderId=[{}]", model.getOrderId());
			} else {
				bean.setCode(0);
				bean.setMessage("申请失败！");
				LOGGER.error("save record error.");
			}
		} catch (Exception e) {
			bean.setCode(0);
			bean.setMessage("申请失败！");
			LOGGER.error("save record error, errorMsg=[{}].", e.getMessage());
		}
		return bean;
	}

	/**
	 * 执行实际的新增操作
	 * 
	 * @param model
	 *            要新增的数据
	 * @return 新增页面逻辑视图
	 */
	@ResponseBody
	@RequestMapping("/get")
	public JsonBean get(String orderId) {
		JsonBean bean = new JsonBean();
		try {
			LOGGER.info("get other pay way, orderId=[{}]", orderId);

			if (StringUtils.isBlank(orderId)) {
				bean.setCode(0);
				bean.setMessage("订单id不能为空！");
				LOGGER.error("orderId is required.");
			}

			Orders orderParam = new Orders();
			orderParam.setOrderId(orderId);

			Orders order = ordersServiceImpl.unique(orderParam);
			bean.setCode(1);
			bean.setData(order);
			bean.setMessage("获取申请结果成功！");
			LOGGER.info("get other pay way success.");
		} catch (Exception e) {
			LOGGER.error("get other pay way error, errorMsg=[{}].", e.getMessage());
			bean.setMessage("获取申请结果失败！");
		}
		return bean;
	}

	@ResponseBody
	@RequestMapping("/uploadMultiFile")
	public JsonBean uploadMultiFile(HttpServletRequest request) {
		JsonBean jsonBean = new JsonBean();

		try {
			String orderId = request.getParameter("orderId");
			String payMethod = request.getParameter("payMethod");

			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			List<MultipartFile> vouchers = (List<MultipartFile>) multipartRequest
					.getFiles("voucher");

			LOGGER.info("request uploadMultiFile, orderId=[{}], payMethod=[{}]", orderId, payMethod);

			if (StringUtils.isBlank(orderId)) {
				jsonBean.setCode(0);
				jsonBean.setMessage("订单id不能为空！");
				LOGGER.error("orderId is required.");
				return jsonBean;
			}

			Orders orderParam = new Orders();
			orderParam.setOrderId(orderId);
			Orders order = ordersServiceImpl.unique(orderParam);

			if (StringUtils.isBlank(payMethod)) {
				jsonBean.setCode(0);
				jsonBean.setMessage("支付方式不能为空！");
				LOGGER.error("payMethod is required.");
				return jsonBean;
			}

			if (null == vouchers || vouchers.size() == 0 || vouchers.size() > 5) {
				jsonBean.setCode(0);
				jsonBean.setMessage("支付凭证1-5张！");
				LOGGER.error("voucher size is 1-5.");
				return jsonBean;
			}

			Voucher voucherParam = new Voucher();
			voucherParam.setOrderId(orderId);
			int clearSize = voucherServiceImpl.deleteBulks(voucherParam);
			LOGGER.info("clear voucher by orderId success, orderId=[{}], clearSize=[{}]", orderId,
					clearSize);

			for (MultipartFile voucher : vouchers) {
				String voucherFilePath = MyFileUtils.uploadImg(voucher, ImgType.ORDER);

				Voucher voucherImage = new Voucher();
				voucherImage.setId(ObjectId.get().toString());
				voucherImage.setOrderId(orderId);
				voucherImage.setOrgId(order.getOrderId());
				voucherImage.setEmployeeId(order.getEmployeeId());
				voucherImage.setFilePath(voucherFilePath);
				voucherImage.setCreateTime(new Date());
				voucherServiceImpl.save(voucherImage);
			}
			LOGGER.info("upload voucher success, size=[{}]", vouchers.size());

			Orders data = new Orders();
			data.setId(order.getId());
			data.setUploadVoucher(true);
			data.setOfflinePay(true);
			data.setPayTime(new Date());
			data.setPaidAmount(order.getOrderAllAmount());
			data.setPayMethod(Integer.parseInt(payMethod));
			data.setState(1);// 已支付

			try {

				// Pad端投资人签订合同成功,提醒投后APP用户
				ordersServiceImpl.createContractMessage(orderId);
				LOGGER.info("send jiguang success");
			} catch (Exception e) {
				LOGGER.error("createContact/send jiguang error, msg=[{}]", e.getMessage());
			}

			ordersServiceImpl.updateById(data);
			LOGGER.info("update order success, orderId=[{}]", orderId);

			jsonBean.setCode(1);
			jsonBean.setMessage("上传凭证成功！");

		} catch (Exception e) {
			jsonBean.setCode(0);
			jsonBean.setMessage("上传凭证失败！");
			LOGGER.error("request uploadMultiFile error, msg=[{}]", e.getMessage());
		}

		return jsonBean;
	}

	@ResponseBody
	@RequestMapping("/uploadMultiFileIOS")
	public JsonBean uploadMultiFileIOS(String orderId, String payMethod, MultipartFile voucher1,
			MultipartFile voucher2, MultipartFile voucher3, MultipartFile voucher4,
			MultipartFile voucher5) {
		JsonBean jsonBean = new JsonBean();

		try {

			LOGGER.info("request uploadMultiFile, orderId=[{}], payMethod=[{}]", orderId, payMethod);

			if (StringUtils.isBlank(orderId)) {
				jsonBean.setCode(0);
				jsonBean.setMessage("订单id不能为空！");
				LOGGER.error("orderId is required.");
				return jsonBean;
			}

			Orders orderParam = new Orders();
			orderParam.setOrderId(orderId);
			Orders order = ordersServiceImpl.unique(orderParam);

			if (StringUtils.isBlank(payMethod)) {
				jsonBean.setCode(0);
				jsonBean.setMessage("支付方式不能为空！");
				LOGGER.error("payMethod is required.");
				return jsonBean;
			}

			int voucherSize = 0;
			if (null != voucher1) {
				voucherSize++;
			}
			if (null != voucher2) {
				voucherSize++;
			}
			if (null != voucher3) {
				voucherSize++;
			}
			if (null != voucher4) {
				voucherSize++;
			}
			if (null != voucher5) {
				voucherSize++;
			}

			if (voucherSize == 0 || voucherSize > 5) {
				jsonBean.setCode(0);
				jsonBean.setMessage("支付凭证1-5张！");
				LOGGER.error("voucher size is 1-5.");
				return jsonBean;
			}

			Voucher voucherParam = new Voucher();
			voucherParam.setOrderId(orderId);
			int clearSize = voucherServiceImpl.deleteBulks(voucherParam);
			LOGGER.info("clear voucher by orderId success, orderId=[{}], clearSize=[{}]", orderId,
					clearSize);

			if (null != voucher1) {
				String voucherFilePath = MyFileUtils.uploadImg(voucher1, ImgType.ORDER);

				Voucher voucherImage = new Voucher();
				voucherImage.setId(ObjectId.get().toString());
				voucherImage.setOrderId(orderId);
				voucherImage.setOrgId(order.getOrderId());
				voucherImage.setEmployeeId(order.getEmployeeId());
				voucherImage.setFilePath(voucherFilePath);
				voucherImage.setCreateTime(new Date());
				voucherServiceImpl.save(voucherImage);
			}
			if (null != voucher2) {
				String voucherFilePath = MyFileUtils.uploadImg(voucher2, ImgType.ORDER);

				Voucher voucherImage = new Voucher();
				voucherImage.setId(ObjectId.get().toString());
				voucherImage.setOrderId(orderId);
				voucherImage.setOrgId(order.getOrderId());
				voucherImage.setEmployeeId(order.getEmployeeId());
				voucherImage.setFilePath(voucherFilePath);
				voucherImage.setCreateTime(new Date());
				voucherServiceImpl.save(voucherImage);
			}
			if (null != voucher3) {
				String voucherFilePath = MyFileUtils.uploadImg(voucher3, ImgType.ORDER);

				Voucher voucherImage = new Voucher();
				voucherImage.setId(ObjectId.get().toString());
				voucherImage.setOrderId(orderId);
				voucherImage.setOrgId(order.getOrderId());
				voucherImage.setEmployeeId(order.getEmployeeId());
				voucherImage.setFilePath(voucherFilePath);
				voucherImage.setCreateTime(new Date());
				voucherServiceImpl.save(voucherImage);
			}
			if (null != voucher4) {
				String voucherFilePath = MyFileUtils.uploadImg(voucher4, ImgType.ORDER);

				Voucher voucherImage = new Voucher();
				voucherImage.setId(ObjectId.get().toString());
				voucherImage.setOrderId(orderId);
				voucherImage.setOrgId(order.getOrderId());
				voucherImage.setEmployeeId(order.getEmployeeId());
				voucherImage.setFilePath(voucherFilePath);
				voucherImage.setCreateTime(new Date());
				voucherServiceImpl.save(voucherImage);
			}
			if (null != voucher5) {
				String voucherFilePath = MyFileUtils.uploadImg(voucher5, ImgType.ORDER);

				Voucher voucherImage = new Voucher();
				voucherImage.setId(ObjectId.get().toString());
				voucherImage.setOrderId(orderId);
				voucherImage.setOrgId(order.getOrderId());
				voucherImage.setEmployeeId(order.getEmployeeId());
				voucherImage.setFilePath(voucherFilePath);
				voucherImage.setCreateTime(new Date());
				voucherServiceImpl.save(voucherImage);
			}
			LOGGER.info("upload voucher success, size=[{}]", voucherSize);

			Orders data = new Orders();
			data.setId(order.getId());
			data.setUploadVoucher(true);
			data.setOfflinePay(true);
			data.setPayTime(new Date());
			data.setPaidAmount(order.getOrderAllAmount());
			data.setPayMethod(Integer.parseInt(payMethod));
			data.setState(1);// 已支付

			try {

				// Pad端投资人签订合同成功,提醒投后APP用户
				ordersServiceImpl.createContractMessage(orderId);
				LOGGER.info("send jiguang success");
			} catch (Exception e) {
				LOGGER.error("createContact/send jiguang error, msg=[{}]", e.getMessage());
			}

			ordersServiceImpl.updateById(data);
			LOGGER.info("update order success, orderId=[{}]", orderId);

			jsonBean.setCode(1);
			jsonBean.setMessage("上传凭证成功！");

		} catch (Exception e) {
			jsonBean.setCode(0);
			jsonBean.setMessage("上传凭证失败！");
			LOGGER.error("request uploadMultiFile error, msg=[{}]", e.getMessage());
		}

		return jsonBean;
	}

}
